package com.xms.schema.service.attribute;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xms.core.exception.XmsException;
import com.xms.datacore.IMetadataProvider;
import com.xms.datacore.service.DeleterService;
import com.xms.dependency.XmsDependencyException;
import com.xms.dependency.service.IDependencyChecker;
import com.xms.event.core.AuthorizationStateChangedEvent;
import com.xms.event.core.IEventPublisher;
import com.xms.schema.core.AttributeDefaults;
import com.xms.schema.entity.Attribute;
import com.xms.schema.entity.RelationShip;
import com.xms.schema.event.AttributeDeletedEvent;
import com.xms.schema.service.entity.IEntityFinderService;
import com.xms.schema.service.relationship.IRelationShipFinderService;
import com.xms.utils.CollectionUtil;
import com.xms.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * AttributeDeleterService
 * </p>
 *
 * @author migo
 * @since 2021/9/2
 */
@CacheConfig(cacheNames = "schema.attribute", keyGenerator = "CacheKeyGenerator")
@Service
public class AttributeDeleterService extends DeleterService<Attribute> implements IAttributeDeleterService {
    private IMetadataProvider _metadataProvider;
    private IEntityFinderService _entityFinderService;
    private IAttributeFinderService _attributeFinderService;
    private IRelationShipFinderService _relationShipFinderService;
    private IAttributeDependency _attributeDependency;
    private IDependencyChecker _dependencyChecker;
    private IEventPublisher _eventPublisher;

    @Autowired
    public void AttributeDeleterService(IMetadataProvider metadataProvider
            , IEntityFinderService entityFinderService
            , IAttributeFinderService attributeFinderService
            , IRelationShipFinderService relationShipFinderService
            , IAttributeDependency attributeDependency
            , IDependencyChecker dependencyChecker
            , IEventPublisher eventPublisher) {
        _metadataProvider = metadataProvider;
        _entityFinderService = entityFinderService;
        _attributeFinderService = attributeFinderService;
        _relationShipFinderService = relationShipFinderService;
        _attributeDependency = attributeDependency;
        _dependencyChecker = dependencyChecker;
        _eventPublisher = eventPublisher;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean deleteById(UUID id) throws SQLException, XmsDependencyException {
        return this.delete(super.getById(id));
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean deleteMany(Wrapper<Attribute> queryWrapper) throws SQLException, XmsDependencyException {
        List<Attribute> deleteds = super.list(queryWrapper);
        if (CollectionUtil.notEmpty(deleteds)) {
            for (Attribute attribute : deleteds) {
                this.delete(attribute);
            }
            return true;
        }
        return false;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean deleteByIds(Collection<UUID> idList) throws SQLException, XmsDependencyException {
        if (CollectionUtil.notEmpty(idList)) {
            List<Attribute> deleteds = super.listByIds(idList);
            for (Attribute attribute : deleteds) {
                this.delete(attribute);
            }
            return true;
        }
        return false;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean delete(Attribute entity) throws SQLException, XmsDependencyException {
        if (entity == null) return false;
        //自定义的字段才允许删除
        if (!entity.getIscustomfield()) return false;
        UUID id = entity.getAttributeid();
        //检查是否存在引用
        _dependencyChecker.checkAndThrow(AttributeDefaults.MODULE_NAME, id);
        boolean success = super.deleteById(id);
        if (success) {
            //List<Attribute> attributes = _attributeFinderService.getByEntityId(entity.getEntityid());
            List<Attribute> attributes = _attributeFinderService.list(new LambdaQueryWrapper<Attribute>().eq(Attribute::getEntityid, entity.getEntityid()));
            //过滤当前记录，以防事务未提交出现脏读
            attributes.removeIf(x -> x.getAttributeid().equals(id));
            List<RelationShip> relationships = _relationShipFinderService.list(new LambdaQueryWrapper<RelationShip>()
                    .eq(RelationShip::getReferencingentityid, entity.getEntityid()));
            //List<RelationShip> relationShips = _relationShipFinderService.getByReferencingEntityId(entity.getEntityid());
            if (relationships != null)
                relationships.removeIf(x -> x.getReferencingattributeid().equals(id));
            //更新视图
            _metadataProvider.alterView(_entityFinderService.getById(entity.getEntityid())
                    , attributes
                    , relationships);
            //删除表字段
            _metadataProvider.dropColumn(entity);
            //删除依赖项
            _attributeDependency.delete(id);
            //权限更改事件
            _eventPublisher.publish(new AuthorizationStateChangedEvent(AttributeDefaults.MODULE_NAME, Collections.singletonList(id), false));
            //删除后事件
            _eventPublisher.publish(new AttributeDeletedEvent(AttributeDefaults.MODULE_NAME, entity));
        }
        return success;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean deleteById(UUID... id) throws SQLException, XmsDependencyException {
        List<Attribute> deleteds = super.listByIds(Arrays.asList(id));
        for (Attribute attribute : deleteds) {
            this.delete(attribute);
        }
        return true;
    }

    @CacheEvict(allEntries = true, condition = "#result == true")
    @Transactional(rollbackFor=Exception.class)
    @Override
    public boolean deleteByEntityId(UUID entityId) throws SQLException, XmsDependencyException {
        if (UUIDUtil.isEmpty(entityId)) {
            return false;
        }
        List<Attribute> attributes = super.list(new LambdaQueryWrapper<Attribute>()
                .eq(Attribute::getEntityid, entityId));
        if(CollectionUtil.isEmpty(attributes))
            return false;
        super.deleteMany(new LambdaQueryWrapper<Attribute>().eq(Attribute::getEntityid, entityId));
        //删除依赖项
        _attributeDependency.delete(attributes.stream().map(x -> x.getAttributeid()).collect(Collectors.toList()).toArray(new UUID[attributes.size()]));
        //发布事件
        for (Attribute attribute : attributes) {
            _eventPublisher.publish(new AttributeDeletedEvent(AttributeDefaults.MODULE_NAME, attribute));
        }
        return true;
    }
}
